<?php
/**
 * Module that manages help articles and organise them.
 *
 */
class Help extends Module {
    protected $name = 'Help';
    protected $administrable = true;
    protected $version = '2009-09-03';
    protected $details = array('dependencies' => array(),
            'observes' => array('Help'));

    const ARTICLES = 'help';

    protected $articlesTable = array('id' => 'iPN+', 'parent' => 'iN',
            'lang' => "v'5'", 'title' => "v'1024'N", 'text' => 'TN');

    protected $articleRecord = array('table' => self::ARTICLES, 'data' =>
            array());

    private $fileCategoryId = 6;

    public function __construct(DBAPI $dbapi, RecordList $recordList) {
        parent::__construct($dbapi, $recordList);
        $this->articleRecord['properties'] = $this->articlesTable;
    }

    public function install() {
        Modules::getModule('Users')->registerRights($this->getName(),
                $this->getRights());
        return $this->dbdriver->createTable(self::ARTICLES,
                $this->articlesTable);
    }

    public function uninstall() {
        return $this->dbdriver->dropTable(self::ARTICLES);
    }

    public function initDisplay($param = null) {
        if (Kernel::getMode() !== Kernel::ADMIN) {
            return;
        }
        $url = Modules::getModule('View')->getUrl();
        if (isset($url[1]) && (($url[1] == 'add') || ($url[1] == 'edit'))) {
            Modules::getModule('View')->addJS(Config::WEB_DIR .
                        '/utils/tiny_mce/tiny_mce.js');
            Modules::getModule('View')->addJS(Config::WEB_DIR . $this->getDir(
                        '/wysiwyg.js', true));
        }
    }

    public function getMetaInfo($property, $url) {
        $url = explode('/', $url);
        if (isset($url[1])) {
            $url = explode('-', $url[1]);
            $url = $url[count($url) - 1];
            $article = $this->articleRecord;
            $article['data']['id'] = $url;
            $this->dbapi->refresh($article);
            return $article['data']['title'];
        }
        return 'Nápověda';
    }

    public function onAdd(&$details, $source) {
        if (!$this->hasRights('create help')) {
            return;
        }
        $article = $this->articleRecord;
        $article['data'] = array('parent' => $details['parent'], 'lang' =>
                $details['lang'], 'title' => $details['title'], 'text' =>
                $details['text']);
        $this->dbapi->save($article);
    }

    public function onEdit(&$details, $source) {
        if (!$this->hasRights('edit help')) {
            return;
        }
        $article = $this->articleRecord;
        $article['data'] = array('id' => $details['id'], 'parent' =>
                $details['parent'], 'lang' => $details['lang'], 'title' =>
                $details['title'], 'text' => $details['text']);
        $this->dbapi->update($article);
    }

    public function onDelete($details, $source) {
        if (!$this->hasRights('delete help')) {
            return;
        }
        $id = (int) substr($details, 0, -1);
        $this->dbdriver->delete(self::ARTICLES, '`id` = ' . $id);
        Kernel::setRedirect($this->getLink());
    }

    public function displayPublicIndex($root) {
        $sub = Modules::getModule('View')->getUrl(null);
        $sub = count($sub) > 0 ? substr($sub[1], strrpos($sub[1], '-') + 1) :
                $root;
        $params = array('order' => array('id'), 'filter' => '`parent` = ' .
                $sub);
        $subarticles = &$this->recordList->getList($this->articleRecord,
                $params);
        foreach ($subarticles as &$subarticle) {
            $subarticle['link'] = $this->getLink(Kernel::createUrl(
                    $subarticle['title']) . '-' . $subarticle['id'] . '/');
        }
        $article = $this->articleRecord;
        $article['data']['id'] = $sub;
        $this->dbapi->refresh($article);
        $params = array('article' => $article['data'], 'subs' => $subarticles);
        $this->template('help', $params);
    }

    public function displayAdminEdit($articleId) {
        if (!$this->hasRights('edit help')) {
            return;
        }
        $article = $this->articleRecord;
        $article['data']['id'] = $articleId;
        $this->dbapi->refresh($article);
        $params = array('form' => array('start' => $this->getForm('edit', true,
                'Help'), 'submit' => 'save', 'items' => array(array('name' =>
                'title', 'label' => 'title', 'value' =>
                $article['data']['title']), array('name' => 'lang', 'label' =>
                'lang', 'value' => $article['data']['lang']), array('name' =>
                'parent', 'type' => 'select', 'label' => 'parent', 'options' =>
                $this->getListForForm(), 'selected' =>
                $article['data']['parent']), array('name' => 'text', 'label' =>
                'text', 'type' => 'textarea', 'cols' => 80, 'rows' => 8,
                'value' => $article['data']['text']), array('name' => 'id',
                'type' => 'hidden', 'value' => $article['data']['id']))),
                'fileCategoryId' => $this->fileCategoryId);
        $this->prepareFormData($params['form']);
        $this->template('articleform', $params);
    }

    public function displayAdminIndex() {
        $articles = &$this->loadArticlesTree();
        $params = array('articles' => $articles);
        $this->template('list', $params);
    }

    public function displayAdminAdd() {
        if (!$this->hasRights('create help')) {
            return;
        }
        $params = array('form' => array('start' => $this->getForm('add', true,
                'Help'), 'submit' => 'create', 'items' => array(array('name' =>
                'title', 'label' => 'title'), array('name' => 'lang',
                'label' => 'lang'), array('name' => 'parent', 'type' =>
                'select', 'label' => 'parent', 'options' =>
                $this->getListForForm()), array('name' => 'text', 'label' =>
                'text', 'type' => 'textarea', 'cols' => 80, 'rows' => 8))),
                'fileCategoryId' => $this->fileCategoryId);
        $this->prepareFormData($params['form']);
        $this->template('articleform', $params);
    }

    public function displayAdminSubmenu() {
        $params = array('menu' => array(array('href' => $this->getLink(),
                'title' => $this->lang('listTitle'), 'label' => $this->lang(
                'list')), array('href' => $this->getLink('add/'), 'title' =>
                $this->lang('addTitle'), 'label' => $this->lang('add'))));
        $this->template('submenu', $params);
    }

    private function &loadArticlesTree($parent = 0, $level = '') {
        $params = array('order' => array('id'), 'filter' => '`parent` = ' .
                $parent);
        $articles = &$this->recordList->getList($this->articleRecord, $params);
        $result = array();
        $i = 1;
        foreach ($articles as &$article) {
            $article['level'] = $level . ($level == '' ? '' : '.') . $i;
            $article['edit'] = $this->getLink('edit/' . $article['id'] . '/');
            $article['delete'] = $this->getLink("{$article['id']}/", 'delete');
            $result[] = $article;
            $sublevel = &$this->loadArticlesTree($article['id'],
                    $article['level']);
            $result = array_merge($result, $sublevel);
            $i++;
        }
        return $result;
    }

    private function getListForForm() {
        $params = array('order' => array('id'));
        $articlesData = &$this->recordList->getList($this->articleRecord,
                $params);
        $articles = array(0 => '-');
        foreach ($articlesData as &$article) {
            $articles[$article['id']] = $article['title'];
        }
        return $articles;
    }
}
?>
